/*
 * @(#)BsTableManager.java
 * 2016年10月19日 下午4:58:17
 * 
 * Copyright (c) 2016 QiYunInfoTech - All Rights Reserved.
 * ====================================================================
 * The QiYunInfoTech License, Version 1.0
 *
 * This software is the confidential and proprietary information of QiYunInfoTech.
 * You shall not disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into with QiYunInfoTech.
 */
package com.qyxx.platform.sysmng.userconfig.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.qyxx.jwp.bean.Module;
import com.qyxx.jwp.bean.ModuleProperties;
import com.qyxx.jwp.datasource.TableEntity;
import com.qyxx.jwp.datasource.TeAttr;
import com.qyxx.platform.sysmng.userconfig.dao.BsFieldDao;
import com.qyxx.platform.sysmng.userconfig.dao.BsFieldInsDao;
import com.qyxx.platform.sysmng.userconfig.dao.BsModuleDao;
import com.qyxx.platform.sysmng.userconfig.dao.BsTableDao;
import com.qyxx.platform.sysmng.userconfig.entity.BsField;
import com.qyxx.platform.sysmng.userconfig.entity.BsModule;
import com.qyxx.platform.sysmng.userconfig.entity.BsTable;
import com.qyxx.platform.sysmng.utils.Constants;

/**
 *  业务表后端逻辑类
 *  @author bobgao
 *  @version 1.0 2016年10月19日 下午4:58:17
 *  @since jdk1.7 
 */
@Component
@Transactional
public class BsTableManager {
	
	public static final Integer CODE_BIT_LEN = 5;//每级编码位数
	
	//根据表ID和字段名查询是否存在字段
	public static final String FIND_BS_FIELD_SQL = "select a from BsField a where a.masterId = ? and a.fieldKey = ?";
	//根据模块key查找表
	public static final String FIND_BS_TABLE_BY_MODULE_KEY = "select a from BsTable a where a.moduleKey = ? order by a.id asc";
	//根据表ID查找字段
	public static final String FIND_BS_FIELD_BY_TABLE_ID = "select a from BsField a where a.masterId = ? and a.isTextField = ? order by a.id asc";
	
	@Autowired
	private BsModuleDao bsModuleDao;
	
	@Autowired
	private BsTableDao bsTableDao;
	
	@Autowired
	private BsFieldDao bsFieldDao;
	
	@Autowired
	private BsFieldInsDao bsFieldInsDao;
	
	/**
	 * 保存业务模块数据
	 * 
	 * @param md
	 * @return
	 */
	public BsModule saveBsModule(Module md) {
		ModuleProperties mp = md.getModuleProperties();
		String moduleKey = StringUtils.lowerCase(mp.getKey());
		List<BsModule> btList = bsModuleDao.findBy("moduleKey", moduleKey);
		BsModule bt = null;
		if(btList.isEmpty()) {
			bt = new BsModule();
			bt.setModuleKey(moduleKey);//模块key小写
			bt.setRefModuleKey(mp.getRelevanceModule());
			bt.setCaption(mp.getCaption());
			bt.setModuleType(mp.getType());
			bt.setVersion(1L);
			bt.setCreateTime(mp.getOwnerProperties().getCreateTime());
			bt.setCreateUser(Constants.SUPER_ADMIN_USER_ID);//默认超级管理员
			bt.setLastUpdateTime(mp.getOwnerProperties().getLastModifiedTime());
			bt.setLastUpdateUser(Constants.SUPER_ADMIN_USER_ID);//默认超级管理员
			bsModuleDao.save(bt);
		} else {
			bt = btList.get(0);
			bt.setRefModuleKey(mp.getRelevanceModule());
			bt.setCaption(mp.getCaption());
			bt.setModuleType(mp.getType());
			bt.setLastUpdateTime(mp.getOwnerProperties().getLastModifiedTime());
		}
		return bt;
	}
	
	/**
	 * 保存实体表数据
	 * 
	 * @param te
	 * @param isUpdate 是否更新数据
	 * @return
	 */
	public String saveBsTable(TableEntity te, Boolean isUpdate) {
		List<BsTable> btList = bsTableDao.findBy("entityName", te.getEntityName());
		BsTable bt = null;
		if(btList.isEmpty()) {
			bt = new BsTable();
			bt.setEntityName(te.getEntityName());
			bt.setTableKey(te.getTableName());
			bt.setModuleKey(StringUtils.split(te.getEntityName(),".")[0]);
			bt.setMasterEntityName(te.getMasterEntityName());
			bt.setCaption(te.getCaption());
			//String systemCode = bsTableDao.getAutoCode("BsTable", "systemCode", null, CODE_BIT_LEN);
			//bt.setSystemCode(systemCode);
			bt.setVersion(1L);
			bt.setCreateTime(new Date());
			bt.setCreateUser(Constants.SUPER_ADMIN_USER_ID);//默认超级管理员
			bsTableDao.save(bt);
			//te.setSystemCode(systemCode);
		} else {
			bt = btList.get(0);
			if(isUpdate) {
				bt.setTableKey(te.getTableName());
				bt.setModuleKey(StringUtils.split(te.getEntityName(),".")[0]);
				bt.setMasterEntityName(te.getMasterEntityName());
				bt.setCaption(te.getCaption());
				bt.setLastUpdateTime(new Date());
				bt.setLastUpdateUser(Constants.SUPER_ADMIN_USER_ID);//默认超级管理员
			}
			//te.setSystemCode(bt.getSystemCode());
		}
		//保存字段
		saveBsField(te, bt, isUpdate);
		return null;
	}
	
	/**
	 * 保存实体业务字段，系统字段不保存
	 * 
	 * @param te
	 * @param bt
	 * @param isUpdate 是否更新数据
	 */
	public void saveBsField(TableEntity te, BsTable bt, Boolean isUpdate) {
		for(TeAttr ta : te.getTeAttr()) {
			if(!ta.getIsSystemAttr()) {//业务字段
				List<BsField> bfList = bsFieldDao.find(FIND_BS_FIELD_SQL, bt.getId(), ta.getColumnName());
				BsField bf = null;
				if(bfList.isEmpty()) {
					bf = new BsField();
					bf.setMasterId(bt.getId());
					bf.setFieldType(BsField.FIELD_TYPE_SYSTEM);//属于系统创建
					bf.setStatus(Constants.STATUS_PASS);
					bf.setTableKey(te.getTableName());
					bf.setEntityName(te.getEntityName());
					
					bf.setModuleKey(bt.getModuleKey());
					bf.setFieldKey(ta.getColumnName());
					bf.setFieldIndex(ta.getFieldIndex());
					if(StringUtils.endsWith(ta.getColumnName(), "Text")) {
						bf.setIsTextField(Constants.BOOL_YES);
					} else {
						bf.setIsTextField(Constants.BOOL_NO);
					}
					
					bf.setCaption(ta.getCaption());
					bf.setDataType(ta.getColumnType());
					bf.setEditType(ta.getEditType());
					bf.setEditDs(ta.getQueryDsSqlKey());
					bf.setDefaultVal(ta.getDefaultVal());
					bf.setExpRule(ta.getExpRule());
					bf.setFormat(ta.getDtFormat());
					bf.setRemark(ta.getHelpMsg());
					
					bf.setVersion(1L);
					bf.setCreateTime(new Date());
					bf.setCreateUser(Constants.SUPER_ADMIN_USER_ID);//默认超级管理员
					
					bsFieldDao.save(bf);
				} else {
					if(isUpdate) {
						bf = bfList.get(0);
						bf.setModuleKey(bt.getModuleKey());
						bf.setFieldKey(ta.getColumnName());
						bf.setFieldIndex(ta.getFieldIndex());
						if(StringUtils.endsWith(ta.getColumnName(), "Text")) {
							bf.setIsTextField(Constants.BOOL_YES);
						} else {
							bf.setIsTextField(Constants.BOOL_NO);
						}
						
						bf.setCaption(ta.getCaption());
						bf.setDataType(ta.getColumnType());
						bf.setEditType(ta.getEditType());
						bf.setEditDs(ta.getQueryDsSqlKey());
						bf.setDefaultVal(ta.getDefaultVal());
						bf.setExpRule(ta.getExpRule());
						bf.setFormat(ta.getDtFormat());
						bf.setRemark(ta.getHelpMsg());
						
						bt.setLastUpdateTime(new Date());
						bt.setLastUpdateUser(Constants.SUPER_ADMIN_USER_ID);//默认超级管理员
					}
				}
			}
		}
	}
	
	/**
	 * 查找表
	 * 
	 * @param moduleKey
	 * @return
	 */
	public List<BsTable> findBsTableByModuleKey(String moduleKey) {
		return bsTableDao.find(FIND_BS_TABLE_BY_MODULE_KEY, moduleKey);
	}
	
	/**
	 * 查找字段
	 * 
	 * @param tableId
	 * @return
	 */
	public List<BsField> findBsFieldByTableId(Long tableId) {
		return bsFieldDao.find(FIND_BS_FIELD_BY_TABLE_ID, tableId, Constants.BOOL_NO);
	}
	
	/**
	 * 根据模块名查找表和对应字段
	 * 
	 * @param moduleKey
	 * @return
	 */
	public List<BsTable> findBsTableFields(String moduleKey) {
		List<BsTable> list = this.findBsTableByModuleKey(moduleKey);
		if(!list.isEmpty()) {
			for(BsTable bt : list) {
				bt.setBsFieldList(this.findBsFieldByTableId(bt.getId()));
			}
		}
		return list;
	}
	
	/**
	 * 检查模块是否修改过，比较最后修改时间
	 * true--更新
	 * @param md
	 * @return
	 */
	public boolean checkBsModuleUpdated(Module md) {
		ModuleProperties mp = md.getModuleProperties();
		String moduleKey = StringUtils.lowerCase(mp.getKey());
		List<BsModule> btList = bsModuleDao.findBy("moduleKey", moduleKey);
		if(!btList.isEmpty()) {
			BsModule bm = btList.get(0);
			Date lmt1 = bm.getLastUpdateTime();
			Date lmt2 = mp.getOwnerProperties().getLastModifiedTime();
			if(lmt1 != null && lmt2 != null) {
				return lmt1.compareTo(lmt2) != 0;
			} else {
				if(lmt1 == null && lmt2 == null) {
					return false;
				} else {
					return true;
				}
			}
		} else {
			return true;
		}
	}

}
